const mongoose = require('mongoose');
const Order = require('../models/Order.model');

//新增
exports.create=function(req,res,next){
    const order = new Order(req.body);
    order.save().then((data)=>{
        res.json(data);
    })
}

exports.update=function(req,res,next){
    const id = req.params.id;
    Order.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data);//这里返回的是修改前的数据，不是修改后的。
    })
}


exports.remove=function(req,res,next){
    const id = req.params.id;
    Order.findByIdAndDelete(id,(err,data)=>{
        res.json(data);
    })
}

exports.list=function(req,res,next){
    var page = req.body.page?req.body.page:1;
    var rows = req.body.rows?req.body.rows:5;
	 
    var queryCondition = {};  //查询条件
    if(req.body.orderid&&req.body.orderid.trim().length>0){
        orderid        = req.body.id;
        queryCondition = {
            "orderid": new RegExp(orderid,'i')
        }
    }
    Order.paginate(queryCondition,{page: + page,limit: + rows},function(err,result){
        result.rows = result.docs;
        delete result.docs;
        if(req.body.product_class){
	    	var someelse=req.body.product_class.split(',').join('|');
		    var myReg=new RegExp(someelse,'i');
		    var myarr=[];
		    for(var i=0;i<result.rows.length;i++){
		    	if(myReg.test(result.rows[i].product_class)){
		    		myarr.push(result.rows[i])
		    	}
		    }
		    result.rows=myarr;
	    }
        res.json(result);
    })
}

exports.getdata=function(req,res,next){
    var id = req.params.id;
    Order.findById(id).then(data=>{
        res.json(data);
    })
}
exports.removes=function(req,res,next){
    var ids = req.body.ids.split(',');
    if(ids.length>0){
        Order.remove({_id:{$in:ids}}).then(data=>{
            res.json({'message':'delete ok',status:200})
        })
    }

}